﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Bitter
{
    /// <summary>
    /// Type that is used to encrypt sensitive data.
    /// </summary>
    public class Protect
    {
        /// <summary>
        /// Protects an text value using the DPAPI.
        /// </summary>
        /// <param name="text">Text to encrypt.</param>
        /// <param name="entropy">Entropy for encryption.</param>
        /// <returns>Base64 encoded encrypted cipher.</returns>
        public static string ProtectText(string text, string entropy)
        {
            byte[] textData = Encoding.UTF8.GetBytes(text);
            byte[] entropyData = Encoding.UTF8.GetBytes(entropy);

            byte[] data = System.Security.Cryptography.ProtectedData.Protect(textData, entropyData, System.Security.Cryptography.DataProtectionScope.CurrentUser);
            string encryptedData = Convert.ToBase64String(data);

            return encryptedData;
        }

        /// <summary>
        /// Unprotects an text value using the DPAPI.
        /// </summary>
        /// <param name="text">Base64 encoded encrypted cipher.</param>
        /// <param name="entropy">Entropy for encryption.</param>
        /// <returns>Decrypted text.</returns>
        public static string UnprotectText(string text, string entropy)
        {
            byte[] encryptedData = Convert.FromBase64String(text);
            byte[] entropyData = Encoding.UTF8.GetBytes(entropy);

            byte[] data = System.Security.Cryptography.ProtectedData.Unprotect(encryptedData, entropyData, System.Security.Cryptography.DataProtectionScope.CurrentUser);
            string textData = Encoding.UTF8.GetString(data);

            return textData;
        }
    }
}
